import router from "@src/router";
import $math from "@src/common/math";
import { discountMd5 } from "@src/common/discountUtils";
import { getQrInfo, getUserPhone, getWxaMsgTpl } from "@src/api/base";
import { createOrder } from "@src/api/catering";
import payBehavior from "./payBehavior";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import cart from "../../store/cart";
import { queryDiscount } from "@src/api/order";
import wxUtils from "@src/common/wxUtils";
import member from "@src/store/member";

const orderTypeName = { 1: '堂食', 2: '外带' }
Component({
  behaviors: [payBehavior, storeBindingsBehavior],
  storeBindings: [{
    store: cart,
    actions: ['clearCart'],
  }, {
    store: member,
    fields: { 'memberPhone': 'phone' },
  }],
  data: {
    shopInfo: null,
    shopId: null,
    tableNo: null,
    cartList: null,
    num: 0,
    orderType: null,
    totalFee: 0,
    isAppointTime: false,
    discountFee: 0,
    orderRemark: "",
    phone: "",
    discountInfo: null,
    tmplIdsData: null,
    isClick: false,
  },
  observers: {
    totalFee() {
      console.log('totalFee', this.data.totalFee)
    }
  },
  methods: {

    onLoad() {
      console.info("order");
      console.log("info")
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('order', (data) => {
        console.info("order", data);
        let { shopInfo, shopId, tableNo, cartList, num, totalFee } = data;
        if (totalFee < 0) {
          totalFee = 0;
        }
        let orderType = shopInfo.orderTypes[0];
        this.setData({ shopInfo, shopId, tableNo, cartList, num, totalFee, orderType });
        this.autoUseDiscount();
      })
      this.fetchData();
    },
    onLogin() {
      if (this.data.memberPhone) {
        this.setData({ phone: this.data.memberPhone })
      }
    },
    fetchData() {
      getWxaMsgTpl({ bizCode: "CANYIN_PLACE_ORDER" }).then(res => {
        if (res.code === 0) {
          let tmplIdsData = res.data;
          this.setData({ tmplIdsData })
        }
      })
    },
    handleChangeOrderType(e) {
      let type = Number(e.currentTarget.dataset.type);
      if (this.data.shopInfo.orderTypes.indexOf(type) === -1) {
        wx.showToast({ title: "该门店暂不支持" + orderTypeName[type], icon: "none", duration: 3000 });
        return
      }
      this.setData({ orderType: type })
    },
    handleSelectCoupon() {
      // 点餐这边的单位都是元...注意单位转换
      router.push({
        name: 'selectDiscount',
        params: {
          shopId: this.data.shopInfo.shopId,
          totalFee: $math.mul(this.data.totalFee, 100, 0),
          orderType: 6,
          selectItem: discountMd5(this.data.discountInfo)
        },
        events: {
          'change': (discountInfo) => {
            console.log("discountInfo", discountInfo)
            this.changeDiscount(discountInfo)
          }
        }
      })
    },
    handleToRemark() {
      router.push({
        name: 'catering/remarks', params: { remark: this.data.orderRemark },
        events: {
          'remarkChange': (remark) => {
            console.info("remarkChange", remark)
            this.setData({ orderRemark: remark })
          }
        }
      })
    },
    handleAppointTime() {
      let data = {
        shopInfo: this.data.shopInfo,
        isAppointTime: this.data.isAppointTime,
        appointMin: this.data.appointMin,
        appointHour: this.data.appointHour
      }
      this.selectComponent("#select-time-dialog").open(data).then(res => {
        console.info("#select-time-dialog", res)
        this.setData({
          isAppointTime: res.isAppointTime,
          appointTime: res.appointTime,
          appointMin: res.appointMin,
          appointHour: res.appointHour
        })
      })
    },
    autoUseDiscount() {
      let totalFee = this.data.totalFee;
      if (totalFee === 0 || totalFee < 0) {
        return 0;
      }
      let data = {
        orderType: 6,
        shopId: this.data.shopInfo.shopId,
        tradeFee: $math.mul(totalFee, 100, 0)
      }
      queryDiscount(data).then(res => {
        if (res.code === 0) {
          if (this.data.totalFee === totalFee && res.data.length > 0) {
            this.changeDiscount(res.data[0]);
          }
        }
      })
    },
    changeDiscount(discountInfo) {
      // 点餐这边的单位都是元...注意单位转换
      if (discountInfo) {
        this.setData({ discountInfo: discountInfo, discountFee: $math.div(discountInfo.discountFee, 100, 2) })
      } else {
        this.setData({ discountInfo: null, discountFee: 0 })
      }
    },
    showScanModal() {
      wx.scanCode({
        success: (scanRes) => {
          let url = scanRes.result;
          if (url && url.indexOf("/") !== -1) {
            let index = url.lastIndexOf("/");
            let codeNo = url.substring(index + 1, url.length);
            this.baseQr(codeNo);
          } else {
            wx.showToast({ title: "无效二维码", icon: "none", duration: 2000 });
          }
        }
      });
    },
    baseQr(codeNo) {
      let data = { codeNo: codeNo };
      getQrInfo(data).then(res => {
        let errMsg = "";
        let data = res.data;
        if (!data || data.bizType !== 1 || !data.bizNo) {
          errMsg = "无效识别码";
        } else if (data.status === 0) {
          errMsg = "识别码未启用";
        } else if (data.bindStatus === 0) {
          errMsg = "识别码未绑定";
        } else if (data.bizShopId !== this.data.shopId) {
          errMsg = "识别码与下单店铺不一致";
        }
        if (errMsg) {
          wx.showModal({
            title: "温馨提示", content: errMsg, showCancel: false, success(res) {
            }
          });
          return;
        }
        wx.showModal({
          content: `当前桌号${data.bizNo}`, cancelText: "重新扫", confirmText: "确认下单",
          success: (res) => {
            if (res.confirm) {
              this.setData({ tableNo: data.bizNo });
              this.handleClickToPay();
            } else if (res.cancel) {
              this.handleClickToPay();
            }
          }
        });
      })
    },
    handlePhoneInput(e) {
      this.setData({ phone: e.detail.value })
    },
    getPhoneNumber(e) {
      console.info("getPhoneNumber", e)
      if (!e.detail.iv) {
        wx.showToast({ title: "手机号获取失败，请重试", icon: "none", duration: 1500 });
        return;
      }
      let data = {
        ivStr: e.detail.iv,
        encryptedData: e.detail.encryptedData,
      }
      getUserPhone(data).then(res => {
        if (res.code === 0) {
          this.setData({ phone: res.data })
        } else {
          wx.showToast({ title: "手机号获取失败，请重试", icon: "none", duration: 1500 });
        }
      })
    },
    //支付按钮点击
    handleClickToPay() {
      let self = this;
      if (!this.data.phone) {
        wx.showToast({ title: "请填写手机号", icon: "none", duration: 1500 });
        return;
      }
      if (this.data.isClick) {
        setTimeout(() => {
          self.setData({ isClick: false })
        }, 1500)
        return;
      } else {
        self.setData({ isClick: true })
      }
      if (!this.data.shopInfo.isUseTableNo || this.data.tableNo) {
        if (this.data.tmplIdsData) {
          wxUtils.requestSubscribeMessage(this.data.tmplIdsData).then(res => {
            this.startCreateOrder()
          }).catch(() => {
            this.startCreateOrder()
          })
        } else {
          this.startCreateOrder()
        }
      } else {
        this.showScanModal();
      }
    },
    startCreateOrder() {
      let data = {
        shopId: this.data.shopId,
        tradeType: 0,
        orderType: this.data.orderType,
        tableNo: this.data.tableNo,
        phone: this.data.phone,
        isAppointTime: this.data.isAppointTime,
        appointHour: this.data.appointHour,
        appointMin: this.data.appointMin,
        remark: this.data.orderRemark,
        items: this.convertCartList(this.data.cartList),
        discountInfo: this.data.discountInfo,
        storeNo:this.data.shopInfo.storeNo
      }
      wx.showLoading({ title: "下单中...", mask: true });
      createOrder(data).then(res => {
        if (res.code === 0) {
          // 清空购物车
          this.clearCart();
          let payChannels = [];
          if (this.data.shopInfo.payTypes.includes(3)) {
            payChannels.push("balance")
          }
          if (this.data.shopInfo.payTypes.includes(1)) {
            payChannels.push("wx")
          }
          let orderNo = res.data.orderNo
          let payFee = $math.mul($math.sub(this.data.totalFee, this.data.discountFee), 100, 0)
          let params = {
            orderNo: res.data.orderNo,
            payFee: payFee > 0 ? payFee : 0,
            hasDiscount: !!this.data.discountInfo,
            payChannels: payChannels
          }
          wx.hideLoading();
          this.toCateringPay(params).then(() => {
            router.redirectTo({ name: "catering/orderdetails", params: { orderNo: orderNo } })
          }).catch(res => {
            router.redirectTo({ name: "catering/orderdetails", params: { orderNo: orderNo } })
          });
        }
      }).catch(res => {
        wx.hideLoading();
      })
    },
    convertCartList(cartList) {
      let rv = [];
      for (let item of cartList) {
        let specs = []
        if (item.spec) {
          specs.push(item.spec)
        }
        specs.push(...item.attrList)
        rv.push({
          itemId: item.id,
          count: item.count,
          specName: item.spec,
          specAttrRemark: specs.join(","),
        })
      }
      return rv;
    }
  },
})
